/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.io.IOException;
import java.util.List;

import kr.pe.johnkim.dayve.provider.DayveLog;
import kr.pe.johnkim.dayve.provider.DayveMember;
import kr.pe.johnkim.dayve.rest.DayveCommonRest;
import kr.pe.johnkim.dayve.rest.DayveMemberRest;
import kr.pe.johnkim.dayve.util.DayveCommon;

import org.json.JSONException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * @author johnkim
 *
 */
public class DayveMileageView extends Activity {
	public static String TAG = DayveMileageView.class.getSimpleName();
	
	private String DAYVE_ID = "";
	private String currentDate = "";
	
	DayveMemberRest dayveMemberRest = new DayveMemberRest();
	DayveCommonRest dayveCommonRest = new DayveCommonRest();
	DayveCommon dayveCommon = new DayveCommon();
	
	ProgressBar progressBarMileage;
	TextView txtViewMileageNotification;
	
	TextView txtViewMileage;
	Button btnMileageEnter;
	
	private String myMileage = "";

	// 프로그레스 바를 출력 한다.
	private static final int THREAD_PROGRESS_BAR_VISIBLE = 101;

	// 프로그레스 바를 감춘다.
	private static final int THREAD_PROGRESS_BAR_INVISIBLE = 102;

	// 마일리지 점수를 가져 온다.
	private static final int THREAD_SELECT_MILEAGE = 103;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dayve_mileage);
		
		confirmNotification();
		
		// 현재 시간을 가져 온다.
		currentDate = dayveCommon.getCurrentDate();
		
		progressBarMileage = (ProgressBar)findViewById(R.id.progressBarMileage);
		txtViewMileageNotification = (TextView)findViewById(R.id.txtViewMileageNotification);
		
		txtViewMileage = (TextView)findViewById(R.id.txtViewMileage);
		txtViewMileage.setText(myMileage);
		btnMileageEnter = (Button)findViewById(R.id.btnMileageEnter);
		btnMileageEnter.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
//		mHandler.sendMessage(mHandler.obtainMessage(THREAD_SELECT_MILEAGE));

	}
	
	/**
	 * SharedPreferences 정보를 확인 한다.
	 */
	public void confirmNotification() {
		String myPf = "kr.pe.johnkim.dayve.activity_preferences";
		SharedPreferences mSharedPreferences = getSharedPreferences(myPf, Activity.MODE_PRIVATE);
		
		// id 를 가져 온다.
		DAYVE_ID = mSharedPreferences.getString("dayve_id", "");
		
		Log.i(TAG, "DAYVE_ID : " + DAYVE_ID);
	}
	
	/**
	 * Handler 를 정의한다.
	 * 모든 Thread 를 등록해 놓고 필요할때 호출한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case THREAD_PROGRESS_BAR_VISIBLE : 
				progressBarMileage.setVisibility(View.VISIBLE);
				txtViewMileageNotification.setVisibility(View.VISIBLE);
				break;
			case THREAD_PROGRESS_BAR_INVISIBLE : 
				progressBarMileage.setVisibility(View.INVISIBLE);
				txtViewMileageNotification.setVisibility(View.INVISIBLE);
				break;
			case THREAD_SELECT_MILEAGE : 
//				threadSelectMileage();
				runOnUiThread(selectMileage);
				break;
			}
		}
	};
	
//	private void threadSelectMileage() {
//		mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_VISIBLE));
//		
//		Thread thread = new Thread(new Runnable() {
//
//			public void run() {
//				// TODO Auto-generated method stub
//				selectMileage();
//			}
//			
//		});
//		
//		thread.start();
//	}
	
//	private void selectMileage() {
//		DayveMember parameterMember = new DayveMember();
//		
//		parameterMember.setId(DAYVE_ID);
//		
//		try {
////			txtViewMileage.setText(dayveMemberRest.selectMileage(parameterMember).getMileage().toString());
//			myMileage = dayveMemberRest.selectMileage(parameterMember).getMileage().toString();
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
//	}
	
	/**
	 * 사용자의 마일리지를 가져 와서 세팅 한다.
	 */
	private Runnable selectMileage = new Runnable() {
		public void run() {
			DayveMember parameterMember = new DayveMember();
			
			parameterMember.setId(DAYVE_ID);
			
			try {
				txtViewMileage.setText(dayveMemberRest.selectMileage(parameterMember).getMileage().toString());
//				myMileage = dayveMemberRest.selectMileage(parameterMember).getMileage().toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		}
	};

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		mHandler.sendMessage(mHandler.obtainMessage(THREAD_SELECT_MILEAGE));
		
		// main thread 에서 child thread 를 호출 한다.
		Thread thread = new Thread(null, insertLogBackgroundThreadProcessing, "Background_insertLog");
		thread.start();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		finish();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(!isForegrdound()) {
			DayvePreferenceView.activity.finish();
			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}

	/**
	 * 로그를 저장 한다.
	 */
	private void insertLog() {
		Log.i(TAG, "insertLog");
		
		DayveLog dayveLog = new DayveLog();
		
		dayveLog.setId(DAYVE_ID);
		dayveLog.setViewName(TAG);
		dayveLog.setAccessDate(currentDate);
		
		try {
			dayveCommonRest.registerLog(dayveLog);
			Log.i(TAG, "Success to insert log.");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		}
	}
	
	/**
	 * 로그 저장은 UI 와 관계 없기 때문에 background thread 로 구현 함 : child thread
	 */
	private Runnable insertLogBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			insertLog();
		}
	};
}
